package com.mlnx.sim.ecg;

import com.mlnx.common.utils.MyLog;
import com.mlnx.mptp.model.ecg.ECGData;
import com.mlnx.mptp.model.ecg.ECGDeviceInfo;
import com.mlnx.mptp.mptp.MpPacket;
import com.mlnx.mptp.mptp.body.Body;
import com.mlnx.mptp.mptp.body.ecg.EcgBody;
import com.mlnx.mptp.mptp.head.QoS;
import com.mlnx.tp.base.model.DeviceType;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import lombok.Data;

/**
 * Created by amanda.shan on 2019/12/27.
 */
@Data
public class PushEcgTimerTask extends TimerTask {

    MyLog log = MyLog.getLog(getClass());

    private String deviceId;
    private MpService mpService;

    private List<byte[]> list;
    Random random = new Random();

    // 注册延迟时间
    private int registerDelayCount = 10;
    private Long sendTime = null;
    private int hasRead = 0;

    private Long flag = null;

    private Long lastSucesstime = null;
    private Map<Integer, Long> sendRecord = new ConcurrentHashMap<>();

    private int messageId = 0;

    public PushEcgTimerTask(String deviceId, List<byte[]> list) {
        this.deviceId = deviceId;
        this.list = list;
        mpService = new MpService(new MpService.CallBack() {
            @Override
            public void pushAck(Integer messageId) {
                Long time = sendRecord.get(messageId);
                if (time != null){
                    lastSucesstime = time;
                    sendRecord.remove(messageId);
                }
            }
        });
        mpService.setDeviceId(deviceId);
    }

    public void copyBytes(byte[] data1, byte[] data2, int index1) {
        for (int i = 0; i < data2.length; i++) {
            data1[index1++] = data2[i];
        }
    }

    @Override
    public void run() {

        try {
            int read = 0;

            if (flag == null) {
                flag = System.currentTimeMillis();
            }

            if (!mpService.isRegister()) {
                registerDelayCount++;
                if (registerDelayCount >= 10) {
                    mpService.register();
                    registerDelayCount = 0;
                    log.info(String.format("%s %s 发送心电注册包", new Date(), deviceId));
                }
            } else {
                registerDelayCount = 0;
                if (sendTime == null) {
                    sendTime = System.currentTimeMillis();
                } else {
                    long diff = System.currentTimeMillis() - sendTime;
                    sendTime = System.currentTimeMillis();

                    EcgBody ecgBody = new EcgBody();
                    Body body = new Body();
                    body.init();
                    if (messageId > 200){
                        messageId = 0;
                    }
                    body.setMessageId(messageId++);
                    body.setDeviceId(deviceId);
                    body.setPacketTime(System.currentTimeMillis());
                    body.setEcgBody(ecgBody);

                    ECGDeviceInfo ecgDeviceInfo = new ECGDeviceInfo();
                    ecgDeviceInfo.setBatteryLevel(random.nextInt(100));
                    ecgDeviceInfo.setSignalStrength(random.nextInt(5));
                    ecgDeviceInfo.setPei(511);
                    ecgBody.setEcgDeviceInfo(ecgDeviceInfo);

                    ECGData ecgData = new ECGData();
                    read = (int) (diff * 500L / 1000L);
                    byte[] bs = new byte[read * 24];
                    int index = 0;

                    for (int k = 0; k < read; k++) {

//                        for (int i = 0; i < 8; i++) {
//                            bs[index++] = 0;
//                            bs[index++] = 8;
//                            bs[index++] = 0;
//                        }
                        copyBytes(bs, list.get(hasRead++), index);
                        index += 24;
                        if (hasRead >= list.size()) {
                            hasRead = 0;
                        }
                    }

                    ecgData.setEncrySuccessionData(bs);
                    ecgBody.setEcgData(ecgData);

                    MpPacket packet = new MpPacket().push(DeviceType.ECG_DEVICE, body);

                    if (System.currentTimeMillis() - flag > 0) {
                        packet.getHeader().setQoS(QoS.LEAST_ONE);
                        flag = System.currentTimeMillis();
                    }

                    sendRecord.put(body.getMessageId(), body.getPacketTime());
                    mpService.push(packet);

//                    log.info(String.format("%s %s 发送心电数据量:%d", DateUtils.format(System.currentTimeMillis(),
//                            "HH:mm:ss:SSS"), deviceId, read));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
